import axios from "axios";
import { ref } from 'vue'
import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from 'vue-router';
export const useHomePageStore = defineStore('homePage', () => {
  const route = useRoute()
  const router = useRouter()
  //获取用户数据
  const userArr = ref([])
  let userId = ref(localStorage.getItem('userId') || null)
  const getUserDate = async () => {
    userId.value = localStorage.getItem('userId')
    let { data } = await axios.get('http://localhost:3000/userList')
    userArr.value = data.find(item => item.id == userId.value)
    return userArr.value
  }


  //用户退出
  const exitUser = () => {
    localStorage.removeItem('userId')
    userArr.value = []
    userId.value = null
    ElMessage.success('退出成功');
    if (route.path.includes('user')||route.path.includes('admin')) {
      router.push('/login')
    }
    if (route.path.includes('main')||route.path.includes('message')) {
      router.push('/home')
    }
  }

  //获取语录
  //语录数据
  const saying = ref('')
  const sayingArr = async () => {
    let { data } = await axios.get('http://localhost:3000/sayingsList')
    saying.value = data[Math.floor(Math.random() * data.length)].text
  }
  return {
    userArr, getUserDate, exitUser, userId, sayingArr, saying
  }
})